<?php
	class Country_model extends MY_Model{
		
		public function __construct(){
			$this->load->database();
		}
		
		public function get_country($iso=FALSE){
			if($iso === FALSE){
				$this->db->select('*');
				$this->db->from('country');
				$this->db->limit($this->record_per_page, $this->limit);
				$query = $this->db->get();
				return $query->result_array();
			}
			$this->db->limit($this->record_per_page, $this->limit);
			$query = $this->db->get_where('country', array('iso' => $iso));
			return $query->row_array();
		}
		
		public function get_country_list(){
			$query = $this->db->get('country');
			return $query->result_array();
		}
		
		public function get_total(){
			return count($this->get_country_list());
		}
		
		public function get_total_search($src=FALSE){
			$this->db->select('*');
			$this->db->from('country');
			$this->db->like('name', $src);
			$this->db->or_like('iso', $src);
			$this->db->or_like('iso3', $src);
			$this->db->or_like('numcode', $src);			
			$query = $this->db->get();				
			return $query->num_rows();
		}
		
		public function search($src=FALSE){
			$this->db->select('*');
			$this->db->from('country');
			$this->db->like('name', $src);
			$this->db->or_like('iso', $src);
			$this->db->or_like('iso3', $src);
			$this->db->or_like('numcode', $src);		
			$this->db->limit($this->record_per_page, $this->limit);
			$query = $this->db->get();				
			return $query->result_array();
		}
		
		public function save(){
			$iso 	= $this->input->post('iso');
			
			$data = array(
				"iso"			=> strtoupper($iso),
				"name_cap" 		=> strtoupper($this->input->post('name')),
				"name" 			=> $this->input->post('name'),				
				"iso3"			=> $this->input->post('iso3'),
				"numcode"		=> $this->input->post('numcode')
			);
			if(empty($iso))
				return $this->db->insert('country', $data);
			else{
				$this->db->where('iso', $iso);
				return $this->db->update('country', $data);
			}
		}
		
		public function delete($iso){
			$sql = "SELECT `id` FROM `city` WHERE `country_code` = $iso";
			$query = $this->db->query($sql);
			if($query->num_rows()==0){
				$this->db->where('iso', $iso);
				$this->db->delete('country');
			}
		}	

		public function check_duplicate_iso($iso=FALSE){
			if($iso!=FALSE){
				$query = $this->db->get_where('country', array('iso' => $iso));
				if($query->num_rows() > 0 )return FALSE;
				else return TRUE;
			}
			else return FALSE;
		}
	}
?>